package com.jdk.demo.pipe;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

// Pipe.SinkChannel类表示Pipe可写入结尾的通道
// Pipe.SourceChannel类表示Pipe可读取结尾的通道
// Pipe类实现单向管道传送的通道对，管道由一对通道组成：一个可写入的sink通道和一个可读取的source通道。一旦将某些字节写入接收器通道，就可以按照与写入时完全相同的顺序从源通道中读取这些字节
public class Test1_1 {

	public static void main(String[] args) throws Exception {
		Pipe pipe = Pipe.open();
		SinkChannel sinkChannel = pipe.sink();
		SourceChannel sourceChannel = pipe.source();

		Thread t1 = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					for (int i = 0; i < 5; i++) {
						sinkChannel.write(ByteBuffer.wrap(("我来自客户端A" + (i + 1) + "\r\n").getBytes()));
					}
				}catch (Exception e) {
					// TODO: handle exception
				}
			}
		};
		t1.start();

		Thread t2 = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					for (int i = 0; i < 5; i++) {
						sinkChannel.write(ByteBuffer.wrap(("我来自客户端B" + (i + 1) + "\r\n").getBytes()));
					}
				}catch (Exception e) {
					// TODO: handle exception
				}
			}
		};
		t2.start();

		Thread.sleep(3000);
		sinkChannel.close();

		ByteBuffer readBuffer = ByteBuffer.allocate(1000);
		int readLength = sourceChannel.read(readBuffer);
		while(readLength != -1) {
			System.out.println(new String(readBuffer.array(), 0, readLength));
			readLength = sourceChannel.read(readBuffer);
		}
		sourceChannel.close();
	}

}
